package juc.day02;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class MyCacheDemo {
    private Map<String,String> map = new HashMap<>();
    private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    private void put(String key,String value){
        rwLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"开始写入key:"+key);
            map.put(key,value);
            TimeUnit.MILLISECONDS.sleep(100);
            System.out.println(Thread.currentThread().getName()+"完成写入key:"+key);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rwLock.writeLock().unlock();
        }
    }
    private void get(String key){
        rwLock.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"开始读取key:"+key);
            map.get(key);
            System.out.println(Thread.currentThread().getName()+"完成读取key:"+key);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rwLock.writeLock().unlock();
        }
    }
    public static void main(String[] args) {
        MyCacheDemo myCacheDemo = new MyCacheDemo();
        for(int i=1;i<=6;i++){
            int finalI = i;
            new Thread(()->{
                myCacheDemo.put(String.valueOf(finalI),String.valueOf(finalI));
            },String.valueOf(i)).start();
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            new Thread(()->{
                for (int j=1;j<=6;j++){
                    int finalJ = j;
                    new Thread(()->{
                        myCacheDemo.get(String.valueOf(finalJ));
                    }).start();
                }
            }).start();
        }
    }
}
